package com.itheima.reggie.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import com.itheima.reggie.entity.Result;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

@Controller
public class FileController {

    @Value("${reggie.path}")
    String path ;

    @RequestMapping("/common/upload")
    @ResponseBody
    public Result<String> upload(MultipartFile file ) throws IOException {
        File file1 = new File(path);
        if( !file1.exists() ){
            //判断文件是否存在
            file1.mkdirs();
            //要是不存在就创建该文件
        }
        String originalFilename = file.getOriginalFilename();
        //获取文件的名字，应该是怕重复，所以就弄一个新的名字，但是要保存后缀名
        String s = FileUtil.extName(originalFilename);
        //获取后缀名
        String s1 = IdUtil.fastUUID();
        String Filename = s1 + "." +s ;
        //文件拷贝
        file.transferTo(new File( path , Filename ));

        //返回文件名
        return Result.success(Filename) ;
    }

    @RequestMapping("/common/download")
    @ResponseBody
    public void download(String name , HttpServletResponse httpServletResponse ) throws IOException {

        FileInputStream fileInputStream = new FileInputStream(path + name );

        ServletOutputStream outputStream = httpServletResponse.getOutputStream();

        //按我理解是输入的流给输出的流
        IOUtils.copy(fileInputStream , outputStream );

        fileInputStream.close();
        outputStream.close();

    }

}
